<template>
	<view class="box d-flex flex-column position-relative overflow-hidden bg-white roundedtx30" :style="{height:windowHeight-100+'px'}">
		<u-toast ref="uToast"></u-toast>
		<view class="position-relative d-flex a-center j-center">
			<view class="d-flex flex-column a-center j-center">
				<view class="d-flex a-center j-center" style="height: 50px;">
					<text class="d-flex" style="font-size: 16px;color: #E56900;margin-bottom: 5px;">支持作者创作，解锁后继续观影</text>
				</view>
			</view>
			<view class="d-flex position-absolute top-0 right-0" @tap.stop="onClose" style="width: 50px;height: 42px;">
				<text class="d-flex position-absolute left-15 bottom-10 iconfont icon-guanbi2 text-black2 font-weight" style="font-size: 16px;"></text>
			</view>
		</view>
		<view class="d-flex flex-row flex-column flex-shrink a-start j-sb px-3" style="height:42px;">
			<view class="d-flex a-center j-center">
				<text class="d-flex" style="color: #3D3D3D;font-size: 30rpx;">解锁{{curInfo.playlet_number?('第'+curInfo.playlet_number):'本'}}集：</text>
				<text class="d-flex"
					style="color: #E56900;font-size: 30rpx;">{{curInfo.amount}}{{coin_name}}</text>
			</view>
			<view class="d-flex a-center j-center" style="font-size: 28rpx;color: #969696;">
				<text>账户余额：{{(userInfo.ml_coin||0)+(userInfo.give_coin||0)}}{{coin_name}}</text>
			</view>
		</view>
		<scroll-view scroll-y="true" :style="{height:windowHeight-150+'px'}">
			<view class="d-flex flex-wrap">
				<view class="item-simulate" :style="{width:windowWidth+'px'}">
					<view class="d-flex list">
						<view v-for="(item,index) in showList" :key="index" :id="item.value"
							class="box box-normal shadow-sm" :style="{width:(windowWidth/2)-20+'px','background-image': 'url('+item.bgtype+')'}" @tap.stop="onclick(index)"
							:class="{'box-active':cur_select_index==index}">
							<text v-if="item.classtext" class="position-absolute top-0 left-0 give" :style="{'background-image': 'linear-gradient(to right,'+item.classbgc+')', color: item.classcolor }">
								{{item.classtext}}
							</text>
							<view class="d-flex flex-column price j-center" :style="{color:item.amountcolor}">
								<view class="d-flex diyprice1 a-end j-center" :style="{color:item.amountcolor}">
									<view class="d-flex a-end" style="height: 40px;">
										<text class="d-flex" style="font-size: 18px;height: 32px;">￥</text>
									</view>
									<text>{{item.amount||0}}</text>
								</view>
								<text v-if="item.give_coin>0" class="diyprice2" :style="{color:item.amountcolor}">
									多送{{handleNum2(item.give_coin)}}元
								</text>
							</view>
							<view v-if="item.type==1" class="diycardfoot" :style="{'background-image': 'linear-gradient(to right,'+item.footcolor+')'}">
								<img style="width: 16px;height: 16px;margin-right: 5px;" :src="item.footicon" alt="" />
								{{handleGetNum(item.amount,item.give_coin)}}
							</view>
							<view v-if="item.foottext && item.type!==1" class="diycardfoot" :style="{'background-image': 'linear-gradient(to right,'+item.footcolor+')'}">
								{{item.foottext}}
							</view>
						</view>
					</view>
				</view>
			</view>
			<view class="d-flex flex-column a-center j-center px-3">
				<text class="d-flex bottomTips text-lightdark">
					温馨提示:
					1.看币或会员属于虚拟产品，充值成功后不支持退换；
					2.未满18周岁的未成年人应在法定监护人指导、同意下进行充值并观看短剧；
					3.不同剧集价格或赠币有差异，以当前页面的价格为准。
				</text>
			</view>
			<view class="d-flex" :style="{height:50+xBarHeight+'px'}"></view>
		</scroll-view>
	</view>
</template>

<script>
	let that,intervalId, count;
	import {
		mapState
	} from 'vuex';
	import tools from "@/utils/tools.js"
	import config from '@/utils/config.js'
	import interfaces from '@/utils/interfaces.js'
	import {
		Decimal
	} from 'decimal.js'
	export default {
		name: "chongzhi",
		props: {
			curInfo: {
				type: Object,
				default: {}
			},
			init: {
				type: Boolean,
				default: false
			},
		},
		data() {
			return {
				showList: [],
				coin_name: uni.getStorageSync(config.coin_name) || '',
				unselect_db_color: '#FCECDE',
				cur_select_index: 0,
				select_db_color: '#E68B3E',
				user_info: {},
				db_biaoqian_tehui: "/static/video/video-cz-tehui.png",
				db_biaoqian_shouchong: "/static/video/video-cz-shouchong.png",
				db_biaoqian_chaozhi: "/static/video/video-cz-chaozhi.png",
			}
		},
		watch: {
			init: {
				handler(newVal) {
					that = this;
					console.log(newVal);
					if (newVal) {
						// this.updateUserInfo();
						this.request({
							url: interfaces.goos_list,
							method: config.post,
							data: {},
							success: (r) => {
								that.showList = r.content.goods_list
								for (var i = 0; i < that.showList.length; i++) {
									if (that.showList[i].is_default === 1) {
										that.cur_select_index = i;
										break;
									}
								}
								console.log('商品列表', r)

							}
						})
					}
				},
				immediate: true,
				deep: true
			}
		},
		computed: {
			...mapState({
				userInfo: state => state.user.userInfo,
				statusBarHeight: state => state.layout.statusBarHeight,
				windowWidth: state => state.layout.windowWidth,
				windowHeight: state => state.layout.windowHeight,
				platform: state => state.layout.platform,
				xBarHeight: state => state.layout.xBarHeight//苹果手机安全区高度
			})
		},
		created() {
			this.$store.commit('mut_initLayout');
			// for (var i = 0; i < 6; i++) {
			// 	let type  = config.cz_type.zheng_chang;
			// 	if(i===0){
			// 		type  = config.cz_type.shou_chong;
			// 	}else if(i===2||i===4){
			// 		type  = config.cz_type.te_hui;
			// 	}else if(i===5){
			// 		type  = config.cz_type.chao_zhi;
			// 	}
			// 	this.showList.push({'cz_type':type,'amount':'69','kandian':'6900','zengsong':'3000','zengsong_shuoming':'多送30元'})
			// }
		},
		methods: {
			handleGetNum(amount, give_coin) {
				if(!amount){ return}
				if (give_coin == 0) {
					return (new Decimal(amount).times(100).toFixed(2).replace(/\.?0+$/, '')) + '看币'
				} else {
					return (new Decimal(amount).times(100).toFixed(2).replace(/\.?0+$/, '')) + '+' + give_coin + '看币';
				}
			},
			handleNum2(num) {
				if (num) {
					let number = new Decimal(num);
					let result = number.times(0.01).toFixed(2);
					result = result.replace(/\.?0+$/, '');
					return result;
				}
			},
			// #ifdef MP-TOUTIAO
			buy(recharge_goods_id,goodstype,playlet_id) {
				console.log(177,goodstype)
				console.log(155,!tt.canIUse('getOrderPayment'))
				if(!tt.canIUse('getOrderPayment')){
					return uni.showToast({title: '当前抖音App版本过低,请升级至最新版本',duration: 3000,icon: "none"});
				}

				let awaittime = 10
				let clickC = uni.getStorageSync('clickC') ? uni.getStorageSync('clickC') : 0 ;
				let releaseTime = uni.getStorageSync('releaseTime') ? uni.getStorageSync('releaseTime') : 0 ;
				if(Number(clickC)==0 ){
					uni.setStorageSync("releaseTime", new Date().getTime())
				}
				if(releaseTime != 0 && releaseTime + 60 * awaittime * 1000 < new Date().getTime()){
					uni.setStorageSync("clickC" , 0)
					uni.setStorageSync("releaseTime" , new Date().getTime())
				}
				
				if(Number(clickC)>=10 ){
					console.log("大于十次")
					if( releaseTime == 0 ){
							uni.setStorageSync("releaseTime", new Date().getTime())
							return uni.showToast({title: '请求过于频繁,请十分钟后再来!',duration: 3000,icon: "none"});
					}
					if(releaseTime != 0 && !(releaseTime + 60 * awaittime * 1000 < new Date().getTime()) ){
							return uni.showToast({title: '请求过于频繁,请十分钟后再来!',duration: 3000,icon: "none"});
					}
					
					if(releaseTime != 0 && releaseTime + 60 * awaittime * 1000 < new Date().getTime() ){
						uni.setStorageSync("clickC" , 0)
						uni.setStorageSync("releaseTime" , new Date().getTime())
					}
				}
				clickC = uni.getStorageSync('clickC') ? uni.getStorageSync('clickC') : 0 ;
				uni.setStorageSync("clickC", clickC + 1 )

				let {platform} = uni.getSystemInfoSync();
				platform = ['android', 'ios'].includes(platform) ? platform : 'android';
				console.log(platform);
				uni.showLoading({
					title: '加载中',
					mask: true
				});
				
				that.request({
					url: interfaces.buy,
					method: config.post,
					data: {
						"recharge_goods_id": recharge_goods_id,
						type:goodstype,
						playlet_id
					},
					success: (r) => {
						console.log(190,r)
						if (r.code === config.SUCCESS) {
							let orderid = r.content.order_id
							tt.requestOrder({
							   data: r.content.data , // 请勿在前端对data做任何处理
							   byteAuthorization: r.content.byteAuthorization, // 请勿在前端对byteAuthorization做任何处理
							   success: (res) => {
							     console.log('200成功', res);
								
								 tt.getOrderPayment({
								    orderId: res.orderId , // 请勿在前端对data做任何处理
								    success: (res) => {
									   uni.hideLoading();
								      console.log('200成功', res);	
									   uni.setStorageSync("clickC",0 )
									   count = 0;
									   intervalId = setInterval(function() {
											if (count < 10) {
												 that.getOrderStaus(orderid,goodstype);
												count++;
											} else {
												uni.hideLoading();
												clearInterval(intervalId); // 清除定时器
											}
										}, 500);
										
									  
								    },
								    fail: (err) => {
								      console.log("203",err.errNo==4);
									  uni.hideLoading();
									  uni.showToast({title: '支付失败',duration: 3000,icon: "none"});
								    },
								  });
								 
							   },
							   fail: (res) => {
							     console.log("2033",res)
								 uni.hideLoading();
								 uni.showToast({title: '获取订单信息失败',duration: 3000,icon: "none"});
							   },
							 });
						} else {
							uni.hideLoading();
							uni.showToast({title: '获取订单信息失败',duration: 3000,icon: "none"});
						}
					}
				})
			},
			// #endif
			
			// #ifdef MP-WEIXIN || MP-KUAISHOU
			// 微信充值支付
			buy(recharge_goods_id,goodstype,playlet_id) {
				let awaittime = 10
				let clickC = uni.getStorageSync('clickC') ? uni.getStorageSync('clickC') : 0 ;
				let releaseTime = uni.getStorageSync('releaseTime') ? uni.getStorageSync('releaseTime') : 0 ;
						
						
				if(Number(clickC)==0 ){
					uni.setStorageSync("releaseTime", new Date().getTime())
				}
				if(releaseTime != 0 && releaseTime + 60 * awaittime * 1000 < new Date().getTime()){
					uni.setStorageSync("clickC" , 0)
					uni.setStorageSync("releaseTime" , new Date().getTime())
				}
				
				
				if(Number(clickC)>=10 ){
					console.log("大于十次")
					if( releaseTime == 0 ){
							uni.setStorageSync("releaseTime", new Date().getTime())
							return uni.showToast({title: '请求过于频繁,请十分钟后再来!',duration: 3000,icon: "none"});
					}
					if(releaseTime != 0 && !(releaseTime + 60 * awaittime * 1000 < new Date().getTime()) ){
							return uni.showToast({title: '请求过于频繁,请十分钟后再来!',duration: 3000,icon: "none"});
					}
					
					if(releaseTime != 0 && releaseTime + 60 * awaittime * 1000 < new Date().getTime() ){
						uni.setStorageSync("clickC" , 0)
						uni.setStorageSync("releaseTime" , new Date().getTime())
					}
				}
				clickC = uni.getStorageSync('clickC') ? uni.getStorageSync('clickC') : 0 ;
				uni.setStorageSync("clickC", clickC + 1 )
				console.log(340,uni.getStorageSync('clickC'),uni.getStorageSync('releaseTime'))
				uni.showLoading({
					title: '加载中',
					mask: true
				});
				that.request({
					url: this.platform == 'android' ? interfaces.buy : interfaces.buy_ios,
					method: config.post,
					data: {
						"recharge_goods_id": recharge_goods_id,
						type:goodstype,
						playlet_id
					},
					success: (r) => {
						if (r.code === config.SUCCESS) {
							let res = r.content || {};
							console.log('充值支付', r);
							if (this.platform == 'android') {
								// #ifdef MP-WEIXIN || MP-KUAISHOU
								that.request({
									url: interfaces.gei_sign,
									method: config.post,
									data: {
										signData: JSON.stringify({
											offerId: config.wxofferId,
											buyQuantity: res.amount,
											env: 0,
											platform: this.platform,
											currencyType: 'CNY',
											outTradeNo: res.order_id,
											attach: '123'
										}),
										mode: 'short_series_coin'
									},
									success: (rr) => {
										uni.hideLoading();
										if (rr.code === config.SUCCESS) {
											let resr = rr.content || {};
											console.log(resr);
											if (this.platform == 'android') {
												const SDKVersion = wx.getSystemInfoSync().SDKVersion;
												if (this.compareVersion(SDKVersion, '2.19.2') >= 0 ||
													wx.canIUse('requestVirtualPayment')) {
													console.warn('微信虚拟支付');
													wx.requestVirtualPayment({
														signData: JSON.stringify({
															offerId: config.wxofferId,
															buyQuantity: res.amount,
															env: 0,
															platform: this.platform,
															currencyType: 'CNY',
															outTradeNo: res.order_id,
															attach: '123'
														}),
														paySig: resr.paySig,
														signature: resr.signature,
														mode: 'short_series_coin',
														success(virtualPayRes) {
															uni.setStorageSync("clickC",0 )
															console.log('11111虚拟支付成功',virtualPayRes);
															uni.showLoading({title: '查询订单中',mask: true});
															count = 0;
															intervalId = setInterval(function() {
																if (count < 10) {
																	that.getOrderStaus(res.order_id,goodstype);
																	count++;
																} else {
																	uni.hideLoading();
																	clearInterval(intervalId); // 清除定时器
																}
															}, 500);
														},
														fail({
															errMsg,
															errCode,
														}) {
															console.log(errCode);
															console.error(errMsg)
															uni.hideLoading();
															if(errCode==-2) return;
															if(errCode==-1){
																uni.showToast({title: '支付失败',duration: 3000,icon: "none"});
															}else{
																uni.showToast({title: '支付失败，错误码：'+errCode,duration: 3000,icon: "none"});
															}
														},
													})
												} else {
													uni.hideLoading();
													uni.showToast({title: '当前客户端版本不支持此支付，请升级微信版本',duration: 3000,icon: "none"});
													console.log(
														'当前用户的客户端版本不支持 wx.requestVirtualPayment')
												}
											} else {
												uni.hideLoading();
												uni.showToast({title: '获取订单信息失败',duration: 3000,icon: "none"});
											}
										}
									},
								})
								// #endif
							}else{
								let provider = '';
								uni.getProvider({
									service: 'oauth',
									success: function(pres) {
										console.log(pres.provider)
										let type, provider;
										if (~pres.provider.indexOf('weixin')) {
											provider = 'wxpay';
										}
										// console.log({
										// 	provider,
										// 	timeStamp: res.timeStamp, //当前的时间
										// 	nonceStr: res.nonceStr, //随机字符串
										// 	package: res.package, //统一下单接口返回的 prepay_id 参数值
										// 	signType: res.signType, //签名算法
										// 	paySign: res.paySign});
										uni.requestPayment({
											provider,
											timeStamp: res.timeStamp, //当前的时间
											nonceStr: res.nonceStr, //随机字符串
											package: res.package, //统一下单接口返回的 prepay_id 参数值
											signType: res.signType, //签名算法
											paySign: res.paySign, //签名
											success(paymentRes) {
												uni.setStorageSync("clickC",0 )
												console.log('成功',paymentRes);
												count = 0;
												intervalId = setInterval(function() {
												    if (count < 10) {
														that.getOrderStaus(res.order_id,goodstype);
												        count++;
												    } else {
														uni.hideLoading();
												        clearInterval(intervalId); // 清除定时器
												    }
												}, 500);
											},
											fail: (res) => {
												uni.hideLoading();
												uni.showToast({title: '支付失败',duration: 3000,icon: "none"});
												console.log('失败',res);
											},
										})
									}
								});
							}
						} else {
							uni.hideLoading();
							uni.showToast({title: '获取订单信息失败',duration: 3000,icon: "none"});
						}
					},
					fail: (e) => {
						uni.hideLoading();
						uni.showToast({
							title: e,
							duration: 2000
						});
					}
				})
			
			},
			// #endif
			getOrderStaus(orderID,goodstype,checkorder=false) {
				that.request({
					url: checkorder?interfaces.dycheckorder:interfaces.order_back,
					method: config.post,
					data: {
						order_id: orderID,
					},
					success: (orderRes) => {
						if (orderRes.code === config.SUCCESS) {
							console.warn('订单状态');
							console.log(orderRes);
							let orderResContent = orderRes.content || false;
							if(orderResContent) {
								uni.hideLoading();
								that.updateUserInfo(false,goodstype);
								if(!checkorder){
									setTimeout(()=>{
										that.$refs.uToast.show({type: 'success',message:'感谢支持，充值成功！',duration:2500});
									},1000)
									if (intervalId) {
										clearInterval(intervalId); // 清除定时器
									}
								}
							}
						}
					},
				})
			},
			compareVersion(_v1, _v2) {
				if (typeof _v1 !== 'string' || typeof _v2 !== 'string') return 0
				const v1 = _v1.split('.')
				const v2 = _v2.split('.')
				const len = Math.max(v1.length, v2.length)

				while (v1.length < len) {
					v1.push('0')
				}
				while (v2.length < len) {
					v2.push('0')
				}
				for (let i = 0; i < len; i++) {
					const num1 = parseInt(v1[i], 10)
					const num2 = parseInt(v2[i], 10)

					if (num1 > num2) {
						return 1
					} else if (num1 < num2) {
						return -1
					}
				}
				return 0
			},
			// type 充值类型 1普通充值 2整剧购买 3VIP充值
			updateUserInfo(init = true,type) {
				tools.get_user_info_by_serve(that, (res) => {
					console.warn(init ? '' : '==22222支付成功！重新获取用户信息===');
					console.log(res);
					if (!init) {
						setTimeout(() => {
							console.warn(`${type==1?'普通充值':type==2?'整剧购买':type==3?'VIP充值':'充值方式为空'}`);
							console.warn('==33333拿到了用户信息，返回解锁===');
							that.$emit('buySuccess',type);
						}, 10)
					}
				})
			},
			onClose() {
				this.$emit('closeCz', {});
			},
			onclick(index) {
				let that=this
				clearTimeout(this.clickTime)
				this.clickTime = setTimeout(() => {
					let {recharge_goods_id,type} = that.showList[index];
					that.buy(recharge_goods_id,type,that.curInfo.playlet_id);
					that.cur_select_index = index;
				    }, 300);
			},
			get_db_color(index) {
				let color = index === this.cur_select_index ? this.select_db_color : this.unselect_db_color
				return color;
			},
			getBqSrc(type) {
				switch (type) {
					case config.cz_type.te_hui: {
						return this.db_biaoqian_tehui;
					}
					case config.cz_type.shou_chong: {
						return this.db_biaoqian_shouchong;
					}
					case config.cz_type.zheng_chang: {
						return '';
					}
					case config.cz_type.chao_zhi: {
						return this.db_biaoqian_chaozhi;
					}
				}

				return '';
			},
			isShowBq(type) {
				return type != config.cz_type.zheng_chang;
			},
			isShowDb(type) {
				return type != config.cz_type.chao_zhi;
			}
		}
	}
</script>

<style lang="scss" scoped>
	.box {
		background: #FFFFFF linear-gradient(to bottom, #FFE1C7 0%, rgba(223, 124, 40, 0) 20%);
	}

	.item-simulate {
		box-sizing: border-box;
		padding: 0px 12px;
	
		.list {
			display: flex;
			flex-wrap: wrap;
			justify-content: space-between;
			align-items: flex-start;
	
			.box {
				height: 120px;
				cursor: default;
				background: #efefef;
				border: 1px solid #f5f5f5;
				border-radius: 15px;
				display: flex;
				position: relative;
				flex-direction: column;
				justify-content: flex-end !important;
				background-repeat: no-repeat;
				background-size: cover;
				padding: 0 !important;
				box-sizing: content-box;
				margin-bottom: 15px;
				align-items: center;
				overflow: hidden;
				.diyprice1{
					width: 100%;
					font-size: 26px;
					margin-top: 6px;
					color: #603013;
				}
				.diyprice2{
					width: 100%;
					display: flex;
					justify-content: center;
					font-size: 12px;
					line-height: 14px;
					margin-top: 4px;
					color: #603013;
				}
				.diycardfoot{
					width: 100%;
					height: 25px;
					display: flex;
					align-items: center;
					justify-content: center;
					position: absolute;
					bottom: 0;
					left: 0;
					font-size: 11px;
					font-weight: 600;
					color: #603013;
				}
				.tip {
					height: 22px;
					font-size: 12px;
					margin: 0;
					color: #bf891c;
				}
	
				.give {
					font-size: 12px;
					margin: 0;
					padding: 4px 16px;
					border-radius: 10px 0px;
					color: #fff;
					font-weight: 600;
				}
	
				.pointer {
					width: 50%;
					height: auto;
					position: absolute;
					bottom: 10px;
					right: -10px;
				}
	
				.price {
					position: absolute;
					top: 20px;
					width: 100%;
					height: 60px;
					font-size: 15px;
					font-weight: 600;
					line-height: 35px;
					margin: 0;
	
					.amountNum {
						font-size: 32px;
						font-style: normal;
						margin-bottom: 3px;
					}
				}
	
				.get {
					width: 100%;
					height: 28px;
					line-height: 28px;
					text-align: center;
					background: linear-gradient(180deg, #fff19d, #ff9e00);
					border-radius: 0 0 5px 5px;
					font-size: 14px;
					color: #583600;
					letter-spacing: 1px;
					font-weight: 500;
					margin: 0px;
				}
			}
	
			.box-normal {
				.price {
					color: #f76f21;
					.dd {
						font-size: 15px;
						color: #f95e5e;
					}
				}
				.get {
					background: #fff7e3;
					color: #bf891c;
				}
			}
	
	
			.box-active {
				border: 1px solid #f97d36;
			}
		}
	}

	.bottomTips {
		font-size: 24rpx;
		margin-bottom: 3px;
	}

	.zc-item-bg {
		background: #FFFFFF;
		border-radius: 10rpx 10rpx 10rpx 10rpx;
		opacity: 1;
		border: 4rpx solid #EDEDED;
	}

	.cz-item-bg {
		background: #FAEAC8;
		border-radius: 10rpx 10rpx 10rpx 10rpx;
		opacity: 1;
		border: 4rpx solid #EDEDED;
	}

	.item-bg {
		background: #FCECDE;
		border-radius: 10rpx 10rpx 10rpx 10rpx;
		opacity: 1;
		border: 4rpx solid #E56900;
	}

	.select-cz-item-bg {
		background: #FAEAC8;
		border-radius: 10rpx 10rpx 10rpx 10rpx;
		opacity: 1;
		border: 4rpx solid #E56900;
	}
</style>